package com.fmatos.amazingwallpapers.service.alarm;

import com.fmatos.amazingwallpapers.service.image.BitmapsService;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

public class AlbumAlarm {

	private static final String TAG = AlbumAlarm.class.getSimpleName();

	public static final String BROADCAST_ACTION_RECURRING = "ALBUM_ALARM_RECURRING_ACTION";
	public static final String BROADCAST_ACTION_DOWNLOAD_INFO = "ALBUM_ALARM_DOWNLOAD_INFO_ACTION";
	public static final String BROADCAST_ACTION_DOWNLOAD_IMAGES = "ALBUM_ALARM_DOWNLOAD_IMAGES_ACTION";
	
	private Context context;
	
	private AlarmManager alarmMgr;
	private PendingIntent alarmIntent;
	
	
	public AlbumAlarm(Context context) {
		this.context = context;
	}
	
	public void setOneTimeAlarm() {
		
		Log.i(TAG,"Schedule service");
		
//		callService(100*1000, BROADCAST_ACTION_DOWNLOAD_INFO); // if calls are too close I cant see the toaster
		callService(5*1000, BROADCAST_ACTION_DOWNLOAD_IMAGES);
	}
	
	private void callService(int interval, String message) 	{
		
		Intent intent = new Intent(context,  BitmapsService.class);
		intent.setAction(message);
		
		alarmIntent = PendingIntent.getService(context, 0, intent, 0);

		alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
		        SystemClock.elapsedRealtime() +
		        interval, alarmIntent);
	}
	
		
	public void setRecurringTimeAlarm() {
		
//		int interval = 15 * 60 * 1000;
//		interval = 5 * 1000; 
		
//		setAlarm(BROADCAST_ACTION_RECURRING,interval);
		Intent intent = new Intent(context, AlbumAlarmReceiver.class);
		intent.setAction(BROADCAST_ACTION_RECURRING);
		alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

		alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		
		alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
				0, AlarmManager.INTERVAL_FIFTEEN_MINUTES, 
				alarmIntent);
		
//		alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
//	            SystemClock.elapsedRealtime() + 3000, 1000, pi);

	}
	
	private void setAlarm(String broadcastAction, int interval) {
		
		Intent intent = new Intent(context, AlbumAlarmReceiver.class);
		intent.setAction(broadcastAction);
		alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

		alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
		        SystemClock.elapsedRealtime() +
		        interval, alarmIntent);
		
	}
	

}
